<template>
  <view class="page-box">
    <view class="header-box">
      <view class="header" :style="{paddingTop: (useAppData.titleHeight+3) + 'px'}">
        <view class="back-box" style="left: 0;" @tap="gotoBack">
          <image class="back-img" src="../../static/icon-back.png"></image>
        </view>
        <span>运动记录</span>
      </view>
      <view class="record-image">
        <img v-if="recordInfo.pathImg" class="guiji" :src="recordInfo.pathImg" />
      </view>
    </view>
    <view class="bottom-info">
      <view class="info">
        <view class="avatar">
          <image :src="state.runData.type === 'share' ? state.avartUrl : state.userInfo?.customers?.headUrl"></image>
        </view>
        <view class="userInfo">
          <view class="name">
            <text>{{state.runData.type === "share" ? state.shareName : state.userInfo?.customers?.customerName}}</text>
            <text class="id-txt" v-if="state.isShareUser">ID: {{recordInfo.userId}}</text>
            <text>{{recordInfo.timePeriod}}</text>
          </view>
          <view class="address">
            <image class="icon" src="../../static/address.png"></image>
            <text>廊坊市体育场</text>
          </view>
        </view>
      </view>
      <view class="time">
        <view class="time-item">
          <text class="value">{{recordInfo.distance}}</text>
          <text class="label">运动里程</text>
        </view>
        <view class="line"></view>
        <view class="time-item">
          <text class="value">{{recordInfo.duration}}</text>
          <text class="label">运动时长</text>
        </view>
        <view class="line"></view>
        <view class="time-item">
          <text class="value">{{recordInfo.pace}}</text>
          <text class="label">平均配速</text>
        </view>
      </view>
      <view v-if="state.isShareUser && recordInfo.maskMobile" class="mobile-box" @tap="onMaskMobile">
        <image class="icon-iphone" :src="recordInfo?.loginType === 'wx' ? '../static/icon-weixin.png' : '../static/icon-iphone.png'"></image>
        <text>{{state.isMaskMobile ? recordInfo.maskMobile : recordInfo.loginMobile }}</text>
      </view>
      <view v-if="state.isShareUser" class="submit" @tap="onSharePoster">打卡分享</view>
      <mCanvas v-if="state.isShareUser" ref="myCanvasRef" :width="336" :height="626" />
    </view>
  </view>
</template>

<script setup>
import {onLaunch, onLoad, onShow, onHide, onUnload, onShareAppMessage, onShareTimeline} from "@dcloudio/uni-app";
import {reactive, ref, onMounted, getCurrentInstance} from "vue"
import * as API from "../../api/api"
import {getTime} from "../../utils/util"
import {storeToRefs} from "pinia";
import { formatSeconds, formatTime } from "../../utils/util"
import {useRunInfoStore} from "../../store/runInfo";
import {useAppStore} from "../../store/app";
import {useShareStore} from "../../store/share";
import {mileageDetail} from "../../api/api";
import {getRandomNumImg} from "../../utils/img";
import mCanvas from "../../components/m-canvas";
import { useCommonStore } from "../../store/common";
import { userLoginStore } from "../../store/userLogin";
const useCommonData = useCommonStore()
const myCanvasRef = ref();
const { proxy, ctx } = getCurrentInstance()
const useShareData = useShareStore()
const useAppData = useAppStore()
const useRunInfoData = useRunInfoStore()
const userLoginData = userLoginStore()
import addressIcon from '../../static/address.png'
const recordInfo = ref({
  createTime: "",
  distance: "",
  duration: 0,
  pace: 0,
  pathImg: "",
  userId: "",
  uuid: "",
})

const onloadData = ref(false)
const state = reactive({
  avartUrl: "https://model-capability.oss-cn-beijing.aliyuncs.com/pro/healthRun/record-boy.png",
  runData: {
    uuid: null,
    type: "user",
    shareDate: proxy.$Moment().format('YYYY-MM-DD HH:mm:ss'),
    shareTotal: 0,
    todayAllMil: 0,
    runAllTime: 0,
    runSpeed: 0,
    runAllMil: 0,
    ranking: 0,
    clockIn: 0,
    randomImg: getRandomNumImg()
  },
  userId: '',
  uuid: '',
  userInfo: null,
  isShareUser: true,
  shareName: null,
  isMaskMobile: true
})

const onMaskMobile = () => {
  state.isMaskMobile = !state.isMaskMobile
}

const createPoster = () => {
  let name = state.runData.type === "share" ? state.shareName : state.userInfo?.customers?.customerName
  name = name.length > 7 ? name.substring(0, 7) + "..." : name
  const allStr = "位全民健康走跑活动的参与者"
  let firstStr = ""
  let lastStr = ""
  const ctx = uni.createCanvasContext('myCanvas')
  ctx.font = '20px'
  ctx.fillStyle = 'rgba(0,0,0,0.8)';
  const metrics = ctx.measureText(state.runData.ranking)
  let rankingWidth = Math.ceil(metrics.width) + 15 || '50'
  let lastTextWidth = 336 - rankingWidth - 210
  let lastTextLeft = rankingWidth + 145
  let allTextWidth = 0
  for(let i = 0; i < allStr.length; i++) {
    let itemMetricsWidth = Math.ceil(ctx.measureText(allStr[i]).width)
    allTextWidth += itemMetricsWidth
    firstStr = allStr.substring(0, i)
    if (allTextWidth >= lastTextWidth) {
      lastStr = allStr.substring(i)
      break;
    }
  }
  // 配置项
  const options = [
    {
      type: "block",
      radius: 8,
      isGradient: true,
      startColor: "#323935",
      endColor: "#323935",
      left: 0,
      top: 80,
      width: 336,
      height: 580,
    },
    // 轨迹图
    {
      type: "image",
      url: recordInfo.value.pathImg,
      left: 0,
      top: 0,
      width: 336,
      height: 500,
    },
    {
      type: "block",
      radius: 0,
      color: "#323935",
      right: 0,
      bottom: 0,
      width: 336,
      height: 240,
    },
    // 头像
    {
      type: "image",
      url: state.userInfo?.customers?.headUrl || state.avartUrl,
      radius: "50%",
      left: 13,
      bottom: 200,
      width: 52,
      height: 52,
    },
    // 名称
    {
      type: "text",
      content: name,
      // maxLine: 1,
      color: "#fff",
      fontSize: 14,
      left: 73,
      bottom: 210,
      width: 100,
      height: 14,
    },
    // 时间
    {
      type: "text",
      content: recordInfo.value.timePeriod,
      color: "#E9F6E3",
      fontSize: 12,
      left: 73,
      bottom: 190,
    },
    // 坐标图
    {
      type: "image",
      url: addressIcon,
      right: 37,
      bottom: 215,
      width: 14,
      height: 17,
    },
    // 地点
    {
      type: "text",
      content: "廊坊市体育场",
      color: "#E9F6E3",
      fontSize: 12,
      right: 14,
      bottom: 185,
    },
    {
      type: "text",
      content: "运动里程",
      color: "#DCDADE",
      // textAlign: "center",
      fontSize: 17,
      width: 110,
      left: 29,
      bottom: 90,
    },
    // 公里数值 state.runData.todayAllMil
    {
      type: "text",
      content: recordInfo.value.distance || "0.00",
      color: "#fff",
      fontSize: 20,
      width: 110,
      // textAlign: "center",
      left: 32,
      bottom: 110,
    },
    // 时间数值
    {
      type: "text",
      content: recordInfo.value.duration || "00:00",
      color: "#fff",
      fontSize: 20,
      width: 110,
      // textAlign: "center",
      left: 142,
      bottom: 110,
    },
    // 配速数值
    {
      type: "text",
      content: recordInfo.value.pace || "0':0''",
      color: "#fff",
      fontSize: 20,
      // textAlign: "center",
      left: 260,
      bottom: 110,
    },
    // 公里
    {
      type: "text",
      content: "运动时长",
      color: "#DCDADE",
      fontSize: 17,
      // textAlign: "center",
      left: 136,
      bottom: 90,
    },
    // 时间
    {
      type: "text",
      content: "平均配速",
      color: "#DCDADE",
      fontSize: 17,
      // textAlign: "center",
      left: 243,
      bottom: 90,
    },
    // 短线
    {
      type: "block",
      radius: 0,
      color: "#2A312A",
      left: 110,
      bottom: 110,
      width: 2,
      height: 17,
    },
    // 短线
    {
      type: "block",
      radius: 0,
      color: "#2A312A",
      right: 110,
      bottom: 110,
      width: 2,
      height: 17,
    },
  ];
  // 调用myCanvas的onDraw方法，绘制并保存
  myCanvasRef.value.onDraw(options, (url) => {
    console.log(url);
  }, () => {});
};

const onSharePoster = () => {
  createPoster()
}

const getRecordDetail = (uuid) => {
  mileageDetail({uuid}).then(res => {
    onloadData.value = true
    if (res.code === 0) {
      recordInfo.value = res.data
      recordInfo.value.duration = formatTime(res.data.duration || 0)
      recordInfo.value.pace = formatSeconds(res.data.pace || 0)
      if (res.data?.distance && res.data.distance * 1000 < 5) {
        uni.showToast({
          title: '您此次运动的轨迹较短，无法生成运动轨迹哦~',
          icon: "none"
        })
      }
    }
  })
}

onShareAppMessage((res) => {
  return useShareData.shareInfo
})
onShareTimeline((res) => {
  return useShareData.shareInfo
})

const gotoBack = () => {
  let optionsSync = uni.getLaunchOptionsSync()
  console.log(optionsSync, state.runData.type, 99900000)
  if (state.runData.type === 'share' || optionsSync?.scene === 1186 || optionsSync?.scene === 1010) {
    uni.redirectTo({
      url: "/pages/chat/chat"
    })
  } else {
    uni.navigateBack()
  }
}
onLoad((options) => {
  console.log("options", options)
  state.userInfo = uni.getStorageSync("userInfo")
    ? JSON.parse(uni.getStorageSync("userInfo"))
    : null;
  state.runData.type = options?.type || "user"
  if (state.runData.type !== "share") {
    state.isShareUser = true
    state.avartUrl = state.userInfo?.customers?.headUrl
  } else {
    state.runData.uuid = options.uuid
    state.shareName = options.name
    state.avartUrl = options.avartUrl
    if (options?.shareUserId && state.userInfo?.customers?.customerId === options?.shareUserId) {
      // 分享者本人进入分享页面
      state.isShareUser = true
    } else {
      // 其他人进入分享者页面
      state.isShareUser = false
    }
  }
})
onShow(() => {
  const pages = getCurrentPages()
  // 获取当前页面实例
  const currentPage = pages[pages.length - 1]
  // 获取页面路径参数
  const options = currentPage.options
  state.uuid = options.uuid
  state.userId = options.userId
  getRecordDetail(options.uuid)

})
onShareAppMessage((res) => {
  console.log("分享给朋友", res, `/examPages/record/detail?shareUserId=${state.userInfo?.customers?.customerId}&&uuid=${state.runData.uuid}&&type=share&&avartUrl=${state.avartUrl}`)
  return {
    title: "2024廊坊首届全民健康走跑大会火热进行中，奔跑廊坊，体育场等你！",
    path: `/examPages/record/detail?shareUserId=${state.userInfo?.customers?.customerId}&&name=${state.userInfo?.customers?.customerName}&&uuid=${state.uuid}&&type=share&&avartUrl=${state.avartUrl}`,
    // mpId: 'xxxx', //此处配置微信小程序的AppId
  };
})
onShareTimeline((res) => {
  let path = `/examPages/record/detail?shareUserId=${state.userInfo?.customers?.customerId}&&name=${state.userInfo?.customers?.customerName}&&uuid=${state.runData.uuid}&&type=share&&avartUrl=${state.avartUrl}`
  console.log("分享到朋友圈=====", path)
  return {
    title: "2024廊坊首届全民健康走跑大会火热进行中，奔跑廊坊，体育场等你！",
    query: `shareUserId=${state.userInfo?.customers?.customerId}&&name=${state.userInfo?.customers?.customerName}&&uuid=${state.runData.uuid}&&type=share&&avartUrl=${state.avartUrl}`,
    // mpId: 'xxxx', //此处配置微信小程序的AppId
  };
})
</script>

<style lang="scss" scoped>
.page-box{
  overflow: hidden;
}
.header-box {
  width: 100vw;
  height: 100vh;
  text-align: center;
  .title {
    font-size: 34rpx;
    color: #000000;
  }
  .header{
    height: 70rpx;
  }
}
.record-image{
  width: 100vw;
  height: 100vh;
  margin-top: 20rpx;
  overflow: hidden;
  .guiji{
    width: 100%;
    height: 100%;
  }
}
.bottom-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  // height: 610rpx;
  background: #323935;
  z-index: 100;
  padding: 0;
  padding-bottom: 60rpx;
  box-sizing: border-box;
  .id-txt{
    padding: 1rpx 0;
  }
  .info{
    display: flex;
    justify-content: flex-start;
    height: 102rpx;
    margin: 0 32rpx;
    .avatar{
      flex-shrink: 0;
      width: 124rpx;
      height: 124rpx;
      margin-top: -22rpx;
      margin-right: 16rpx;
      border-radius: 124rpx;
      overflow: hidden;
      image{
        width: 100%;
        height: 100%;
      }
    }
    .userInfo{
      flex: 1;
      flex-shrink: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .name{
        flex: 1;
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;
        padding-top: 35rpx;
        color: rgba(255,255,255,0.8);
        font-size: 24rpx;
        text:first-child{
          width: 350rpx;
          height: 44rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 32rpx;
          color: #FFFFFF;
          line-height: 44rpx;
          text-align: left;
          font-style: normal;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
        text:last-child{
          height: 34rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: rgba(255,255,255,0.8);
          line-height: 34rpx;
          text-align: left;
          font-style: normal;
        }
      }
      .address{
        width: 190rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: -32rpx;
        flex-shrink: 0;
        .icon{
          width: 32rpx;
          height: 40rpx;
          margin-right: 10rpx;
        }
        text{
          height: 34rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: rgba(255,255,255,0.8);
          line-height: 34rpx;
          text-align: right;
          font-style: normal;
        }
      }
    }
  }
  .mobile-box{
    width: 244rpx;
    height: 60rpx;
    background: #272F2A;
    border-radius: 30rpx;
    font-size: 24rpx;
    color: rgba(255,255,255,0.8);
    padding: 12rpx 32rpx;
    margin: 0 auto 44rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .icon-iphone{
      width: 36rpx;
      height: 36rpx;
    }
  }
  .time{
    height: 106rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 68rpx 52rpx;
    .time-item{
      .value{
        display: block;
        height: 58rpx;
        font-family: SFCompactDisplay, SFCompactDisplay;
        font-weight: bold;
        text-align: center;
        font-size: 48rpx;
        color: #FFFFFF;
        line-height: 58rpx;
        font-style: normal;
      }
      .label{
        display: block;
        height: 40rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #DCDADE;
        line-height: 40rpx;
        text-align: center;
        font-style: normal;
        margin-top: 16rpx;
      }
    }
  }
  .submit{
    width: 686rpx;
    height: 92rpx;
    margin: 0 auto;
    background: #08CB8F;
    border-radius: 16rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 32rpx;
    color: #FFFFFF;
    line-height: 92rpx;
    text-align: center;
    font-style: normal;
  }
  .line{
    width: 4rpx;
    height: 40rpx;
    background: #2A312A;
    border-radius: 2rpx;
  }
}
</style>
